package com.bestv.search.common.dao.hibernate;

import com.bestv.search.common.dao.KeySubjectDao;
import com.bestv.search.common.model.KeySubject;
import org.hibernate.*;
import org.springframework.orm.hibernate3.HibernateCallback;

import java.sql.SQLException;
import java.util.*;

public class KeySubjectDaoHibernate extends GenericDaoHibernate<KeySubject, Long> implements KeySubjectDao {

    public KeySubjectDaoHibernate() {
        super(KeySubject.class);
    }

    @Override
    public KeySubject getByTypeName(final String type, final String name) {
        return (KeySubject) getHibernateTemplate().execute(new HibernateCallback() {
            public Object doInHibernate(Session session) throws HibernateException, SQLException {
                final String hql = "from KeySubject ks where ks.p_type=:type and ks.name=:name";
                Query query = session.createQuery(hql);
                query.setString("type", type);
                query.setString("name", name);
                return query.uniqueResult();
            }
        });
    }

    @Override
    public List<KeySubject> getKeySubjects() {
        return super.getAll();
    }

    @SuppressWarnings("unchecked")
    @Override
    public Map<String, Integer> findKeyFrequent(final String[] keys) {
        return (Map<String, Integer>) super.getHibernateTemplate().execute(new HibernateCallback() {
            public Map<String, Integer> doInHibernate(Session session) throws HibernateException, SQLException {
                StringBuffer sb = new StringBuffer("select keyword,count(key_id) as num from ");
                sb.append("(select id from info where info.update_flag != 2) as temp_info ");
                sb.append("inner join info_key on temp_info.id = info_key.info_id ");
                sb.append("inner join (select * from keyword ");
                if (keys != null && keys.length > 0) {
                    sb.append("where keyword in (");
                    for (String s : keys)
                        sb.append("'").append(s).append("'").append(",");
                    sb.deleteCharAt(sb.lastIndexOf(","));
                    sb.append(")");
                }
                sb.append(") as temp_key on info_key.key_id = temp_key.id ");
                sb.append("group by key_id order by num desc");
                log.debug(sb.toString());
                SQLQuery sqlQuery = session.createSQLQuery(sb.toString());
                log.debug(sb.toString());
                sqlQuery.addScalar("keyword", Hibernate.STRING).addScalar("num", Hibernate.INTEGER);
                Iterator<Object[]> it = sqlQuery.list().iterator();
                Map<String, Integer> mp = new HashMap<String, Integer>();
                while (it.hasNext()) {
                    Object[] rows = it.next();
                    mp.put(String.valueOf(rows[0]), new Integer(String.valueOf(rows[1])));
                }
                if (mp == null || mp.size() == 0) {
                    for (String ks : keys)
                        mp.put(ks, 0);
                }
                List<String> zeroStrings = new ArrayList<String>();
                Set<String> keyset = mp.keySet();
                l1:
                for (String s : keys) {
                    int k = 0;
                    for (String ks : keyset) {
                        k++;
                        if (s.equals(ks)) {
                            continue l1;
                        }
                        if (k == keyset.size())
                            zeroStrings.add(s);
                    }
                }
                for (String zs : zeroStrings)
                    mp.put(zs, 0);
                return mp;
            }
        });
    }

    @Override
    public KeySubject deleteById(Long id) {
        return super.remove(id);
    }

    @SuppressWarnings("unchecked")
    @Override
    public List<KeySubject> getKeySubjectsPaging(final int start, final int limit) {
        return (List<KeySubject>) getHibernateTemplate().execute(new HibernateCallback() {
            public Object doInHibernate(Session session) throws HibernateException, SQLException {
                String hql = "from KeySubject";
                Query query = session.createQuery(hql);
                query.setFirstResult(start);
                query.setMaxResults(limit);
                return query.list();
            }
        });
    }

    @Override
    public int getKeySubjectCount() {
        return (Integer) getHibernateTemplate().execute(new HibernateCallback() {
            @SuppressWarnings("unchecked")
            public Object doInHibernate(Session session) {
                String HQL = "from KeySubject";
                Query query = session.createQuery(HQL);
                List<KeySubject> list = query.list();
                if (list == null)
                    return 0;
                return list.size();
            }
        });
    }

    @Override
    public int getOnLineKeySubjectsCount() {
        String sql = "select count(*) from key_subject where update_flag<2";
        Session session = null;
        try {
            Query query = getSession().createSQLQuery(sql);
            List<?> list = query.list();

            if (list != null && list.size() > 0) {
                return Long.valueOf(list.get(0).toString()).intValue();
            }

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (session != null)
                releaseSession(session);
        }
        return 0;
    }

    @SuppressWarnings("unchecked")
    @Override
    public List<KeySubject> getOnLineKeySubjects(int start, int limit) {
        String hql = "from KeySubject ks where ks.updateFlag < 2 order by ks.updateTimeForIndex asc";
        Session session = null;
        List<KeySubject> keys = null;
        try {
            Query query = getSession().createQuery(hql);
            query.setFirstResult(start);
            query.setMaxResults(limit);
            keys = query.list();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (session != null)
                releaseSession(session);
        }
        return keys;
    }

    @SuppressWarnings("unchecked")
    @Override
    public List<KeySubject> getKeySubjectsByUpdateTimeForIndex(Date updateTimeForIndex) {
        String hql = "from KeySubject ks where ks.updateFlag < 2 and ks.updateTimeForIndex >:updateTimeForIndex "
                + "order by ks.updateTimeForIndex asc";
        Session session = null;
        List<KeySubject> keys = null;
        try {
            Query query = getSession().createQuery(hql);
            query.setTimestamp("updateTimeForIndex", updateTimeForIndex);
            keys = query.list();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (session != null)
                releaseSession(session);
        }
        return keys;
    }
}
